<template>
    <div id="canvas" ref="root">
        <div class="ui_container">
            <!--logo UI-->
            <div class="logo">
                <a href="https://www.iddd.com/" target="_blank">
                    <img src="../assets/IDDDLogo.png" alt="">
                </a>
            </div>
            <!--底部工具菜单UI-->
            <div class="tool">
                <el-tooltip class="item" effect="dark" content="工具箱" placement="top" :enterable="false">
                    <el-button type="primary" icon="iconfont iconai-tool" @click="toolEdit"></el-button>
                </el-tooltip>

                <el-tooltip class="item" effect="dark" content="商品清单" placement="top" :enterable="false">
                    <el-button type="primary" icon="iconfont iconshangpinqingdan" @click="productShow"></el-button>
                </el-tooltip>

                <el-tooltip class="item" effect="dark" content="分享" placement="top" :enterable="false">
                    <el-button type="primary" icon="iconfont iconfenxiang" @click="shareScene"></el-button>
                </el-tooltip>

                <el-tooltip class="item" effect="dark" content="关于" placement="top" :enterable="false">
                    <el-button type="primary" icon="iconfont icongongsi" @click="showAboutUs"></el-button>
                </el-tooltip>

                <el-tooltip class="item" effect="dark" content="预约设计" placement="top" :enterable="false">
                    <el-button type="primary" icon="iconfont iconshejishi" @click="contactUsDesign"></el-button>
                </el-tooltip>

                <!--<el-tooltip class="item" effect="dark" content="更多" placement="top" :enterable="false">-->
                <!--<el-button type="primary" icon="iconfont icongengduo" @click="moreOperation"></el-button>-->
                <!--</el-tooltip>-->

            </div>


            <!--工具箱-->
            <el-dialog title="工具箱" :modal="false" :visible.sync="toolsDialogVisible" @close="toolsDialogClose">

                <el-card>

                    <el-row>
                        <p>阳光开关:</p>
                        <el-switch
                                v-model="sunLightSwitch"
                                @change="sunLightSwitchChange">
                        </el-switch>
                    </el-row>

                    <el-row>
                        <p>日照分析:</p>
                        <el-switch
                                v-model="isSunlightAutoRotate"
                                @change="sunLightAutoRotateSwitchChange">
                        </el-switch>
                    </el-row>

                    <el-row>
                        <p>漫游模式(WASD):</p>
                        <el-switch
                                v-model="isRoam"
                                @change="roamSwitchChange">
                        </el-switch>
                    </el-row>

                    <el-row>
                        <p>阳光强度:</p>
                        <el-slider
                                v-model="sunLightIntensity"
                                :min="0"
                                :max="20"
                                @change="sunLightIntensityChange">
                        </el-slider>
                    </el-row>

                    <el-row>
                        <p>阳光颜色:</p>
                        <el-color-picker v-model="sunLightColor" @change="sunLightColroChange"></el-color-picker>
                    </el-row>

                    <el-row>
                        <el-button type="primary" @click="resetView">重置视野</el-button>
                    </el-row>

                </el-card>

            </el-dialog>

            <!--商品清单-->
            <el-dialog title="商品清单" width="100%" :visible.sync="productsDialogVisible" @close="productsDialogClose">

                <el-card v-for="productinfo in productInfos" :key="productinfo.id" class="productItem">
                    <el-image :src="productinfo.url" style="width: 30%; height: 30%; margin:5px" lazy>
                        <div slot="error" class="image-slot">
                            <i class="el-icon-picture-outline"></i>
                        </div>
                    </el-image>
                    <div class="productInfo">
                        <el-row>
                            商家:iddd
                        </el-row>
                        <el-row>
                            <!--名字:iddd 商品-->
                            名字: {{productinfo.ChineseName | ellipsis}}
                        </el-row>
                    </div>
                    <el-button type="warning" class="productBuyBtn" @click="productBuy">购买</el-button>
                </el-card>

            </el-dialog>

            <!--分享二维码-->
            <el-dialog title="分享" :visible.sync="shareDialogVisible" @close="shareDialogClose">
                <div id="qrcode">

                </div>
            </el-dialog>

            <!--关于我们-->
            <el-dialog title="关于我们" width="80%" :visible.sync="aboutUsVisible" @close="aboutUsClose">

                <el-card class="box-card">
                    <p class="aboutUsP">
                        宅景是一家为房屋产业链提供整体解决方案的互联网软件公司，我们开发的宅景设计师软件以信息化可视化3D技术为基础，为房屋产业链提供设计、沟通、营销、生产、管理等服务来提升行业效率，为房屋产业链的每一个细分领域赋能，为智能家居和智能物联网助力。
                        宅景设计师软件可以实现房屋产业链中多个细分领域的自由绘制，包括：户型、暖通、橱柜、门窗、地面、墙面、吊顶、楼梯、淋浴房、阳光房、屋顶、花园等等，实现全屋定制，这些细分方向的设计师也可以相互配合，将自己设计的橱柜、楼梯、淋浴房等模块融入到业主的整体房型中去，使业主有更清晰直观的认识，提升沟通效率和成单率。
                        宅景设计师支持Mac系统和Windows系统的PC端下载安装，还支持IOS和Android的移动端下载安装，包括手机版和Pad版，满足用户不同场景的沟通需求。
                        宅景设计师可以使业主通过软件参与到设计方案中，对自己未来居所的情况提前预知和调整，提升满意度，为业主与装修公司之间搭建了一个友好沟通的桥梁。
                        宅景设计师还为这些细分领域提供自动出图纸及拆单算料的功能，使细分领域的从业者可以用最快的方式实现设计到生产的信息化、流程化管控。</p>
                </el-card>
            </el-dialog>

            <!--预约设计弹框-->
            <el-dialog title="预约设计" :visible.sync="contactUsDesignVisible" @close="contactUsDesignClose">
                <el-form :model="contactUsDesignform">
                    <el-form-item label="公司名称">
                        <el-input v-model="contactUsDesignform.company" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="联系地址">
                        <el-input v-model="contactUsDesignform.address" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="电话">
                        <el-input v-model="contactUsDesignform.phone" disabled></el-input>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>

<script>
  import QRCode from 'qrcodejs2'  // 引入qrcode
  import * as THREE from 'three'
  // let THREE=require('three');
  import {FBXLoader} from "../../node_modules/three/examples/jsm/loaders/FBXLoader.js"
  import {WEBGL} from "../../node_modules/three/examples/jsm/WebGL.js"
  import MainScene from "../core/ShareWeb/MainScene";
  import {SupLoader} from "../core/ShareWeb/SupMgr"
  import SkyBoxMgr from "../core/ShareWeb/SkyBoxMgr";
  import {Loading} from 'element-ui';

  export default {
    name: "Canvas",
    data() {
      return {
        DoPromise: false,
        clock:new THREE.Clock(),
        scene: null,
        supLoader: null,
        sunLightSwitch: true,
        isSunlightAutoRotate:false,
        isRoam:false,
        sunLightIntensity: 3,
        sunLightColor: '#ffffff',
        productInfos: [],
        toolsDialogVisible: false,
        productsDialogVisible: false,
        shareDialogVisible: false,
        aboutUsVisible: false,
        contactUsDesignVisible: false,
        contactUsDesignform: {
          company: '上海宅景科技',
          address: '联航路',
          phone: '13331992253'
        },
        loadingInstance: null,
        qrcode: null,
        qrcodeUrl: 'https://www.iddd.com/',
        canvasInfo: {
          id: 'test'
        }
      };
    },
    created() {
      // this.loadingInstance =this.$loading.service({fullscreen: true, text: '拼命加载中'});
      this.loadingInstance = Loading.service({fullscreen: true, text: '拼命加载中'});
      if (WEBGL.isWebGLAvailable()) {
        this.$nextTick(this.init);
      } else {
        var warning = WEBGL.getWebGLErrorMessage();
        console.log(warning);
        this.$message.error("不支持WebGL,请使用谷歌浏览器");
      }
    },
    mounted() {


    },
    filters: {
      ellipsis (value) {
        if (!value) return ''
        if (value.length > 15) {
          return value.slice(0,15) + '...'
        }
        return value
      }
    },
    methods: {


      //得到商品列表
      GetProductList: function (response, fbxIconBaseUrl) {

        let id=0;
       let productUrl=[];
        const contains = (() =>
            Array.prototype.includes
              ? (arr, value) => arr.includes(value)
              : (arr, value) => arr.some((el => el === value))
        )();


        // console.log('sup response', response)

        const data = response.data;
        const MaterialNodes = data.MaterialNodes;
        const Products = data.Products;

        for (var i = 0; i < MaterialNodes.length; i++) {
          if (MaterialNodes[i].TextureUrl !== null) {
            if (!contains(productUrl, MaterialNodes[i].TextureUrl)) {
                  let textureDic = {};
                  textureDic['id'] = id++;
                  textureDic['url'] = MaterialNodes[i].TextureUrl;
                  // textureDic['ChineseName'] = MaterialNodes[i].TextureChineseName;
                  textureDic['ChineseName'] = 'iddd 商品'+id;
                  // console.log('textureDic',textureDic);
                  this.productInfos.push(textureDic);
                  productUrl.push(MaterialNodes[i].TextureUrl);
            }
          }
        }


        for (var j = 0; j < Products.length; j++) {
          const productFullUrl = fbxIconBaseUrl + Products[j].Url + '.jpg';
          if (!contains(productUrl, productFullUrl)) {
                console.log(productFullUrl);
                let productDic = {};
                productDic['id'] = id++;
                productDic['url'] = productFullUrl;
                // productDic['ChineseName'] = Products[j].ChineseName;
                productDic['ChineseName'] = 'iddd 商品'+id;
                this.productInfos.push(productDic);
                productUrl.push(productFullUrl);
          }
        }

      },

      //初始化Canvas
      init() {
        console.log(this.$route)
        this.canvasInfo.id = this.$route.params.id;
        const ossBaseUrl = 'http://iddd.oss-cn-shanghai.aliyuncs.com/';
        const shareModelUrl = ossBaseUrl + 'LocalDB/ShareModel/';
        const skyBoxbaseUrl = ossBaseUrl + "sheji/public/model/iddd/skyboxs/sky5/";
        const fbxBaseUrl = ossBaseUrl + "sheji/public/model/";
        const fbxIconBaseUrl = ossBaseUrl + "sheji/public/model_icons/";
        let supUrl = shareModelUrl + this.canvasInfo.id + ".sup";
        let buildingUlr = shareModelUrl + this.canvasInfo.id + ".fbx";
        this.scene = new MainScene();
        if (this.DoPromise) {
          this.IdddPromise(supUrl, skyBoxbaseUrl, fbxBaseUrl, buildingUlr);
        }
        else {

          this.$http.get(supUrl).then(response => {

            this.GetProductList(response, fbxIconBaseUrl);


            //旧版本加载天空盒，模型，贴图
            // this.loadSkyBox(skyBoxbaseUrl)

            this.scene.createCharacter(fbxBaseUrl+"iddd/ogro/");
            this.scene.character.root.visible=this.isRoam;
            this.scene.orbitControls.enableKeys=this.isRoam;

            this.scene.createSkyBox(skyBoxbaseUrl);
            this.supLoader = new SupLoader(supUrl, fbxBaseUrl);
            this.scene.add(this.supLoader.productMgr.root);
            this.supLoader.init(() => this.scene.loadBuilding(buildingUlr, this.supLoader));
            this.AfterResourceRequestFinished();

          }).catch(error => {
            console.log("sup error:", error)
          })
        }
      },

      //天空盒Promise
      GetSkyBoxPromise(skyBoxUrl) {
        return new Promise((resolve, reject) => {
          SkyBoxMgr.getInstance().createSkyBoxAsync(skyBoxUrl).then(textureCube => {
            resolve(textureCube);
          }).catch(error => {
            console.error('loadSkyBox error:' + error);
            reject(error);
          });
        });
      },
      //supFile
      GetSupFilePromise(supUrl) {
        return new Promise((resolve, reject) => {
          let loader = new THREE.FileLoader(THREE.DefaultLoadingManager);
          loader.setResponseType('arraybuffer');
          loader.loadAsync(supUrl).then(buffer => {
            resolve(buffer);
          }).catch(error => {
            console.error('supFile error:' + error);
            reject(error);
          });
        });
      },
      //house FBX
      GetBuildingPromise(buildingUlr) {
        return new Promise((resolve, reject) => {
          let loader = new FBXLoader();
          loader.loadAsync(buildingUlr).then(buildFbx => {
            resolve(buildFbx);
          }).catch(error => {
            console.error('building error:' + error);
            reject(error);
          });
        });
      },
      //异步加载
      IdddPromise(supUrl, skyBoxUrl, fbxBaseUrl, buildingUlr) {
        this.supLoader = new SupLoader(supUrl, fbxBaseUrl);
        this.scene.add(this.supLoader.productMgr.root);
        const skyBoxPromise = this.GetSkyBoxPromise(skyBoxUrl);
        const supFilePromise = this.GetSupFilePromise(supUrl);
        const buildingPromise = this.GetBuildingPromise(buildingUlr);
        Promise.all([skyBoxPromise, supFilePromise]).then((resultList) => {

          // console.warn(resultList.length)
          // console.warn("resultList:"+resultList)
          // console.warn(resultList[0])
          // console.warn(resultList[1])

          //天空盒 加载成功
          let textureCube = resultList[0];
          textureCube.format = THREE.RGBFormat;
          textureCube.mapping = THREE.CubeReflectionMapping;
          textureCube.encoding = THREE.sRGBEncoding;
          this.scene.background = textureCube;

          //supFile 加载成功
          let buffer = resultList[1];
          let content = String.fromCharCode.apply(null, new Uint8Array(buffer))
          let supFileobj = (JSON.parse(content));
          // console.warn("MaterialNodes:")
          // console.log(supFileobj.MaterialNodes)


          let TexturesPromise = this.supLoader.materialMgr.loadAsync(supFileobj.MaterialNodes);
          //材质贴图 加载成功
          TexturesPromise.then(textureList => {
            for (var index in textureList) {
              let tx2d = textureList[index];
              // console.log(tx2d);
              this.supLoader.materialMgr.createMaterialBySingle(this.supLoader.materialMgr.getHaveTextureMaterialNodes()[index], tx2d);
            }

            let fbxPromises = this.supLoader.productMgr.loadAsync(supFileobj.Products, fbxBaseUrl);
            //模型 加载成功
            fbxPromises.then(fbxList => {
              // console.log(fbxList);
              // console.log(fbxList.length);
              for (let index = 0; index < supFileobj.Products.length; index++) {
                const product = supFileobj.Products[index];
                console.log("product")
                console.log(product)
                console.log(fbxList[index])
                let obj = fbxList[index].clone();
                console.log("obj");
                console.log(obj);
                console.log(typeof  obj);
                let matrix = this.supLoader.productMgr.calMatrix(product.T, product.R, product.S);
                obj.applyMatrix4(matrix);
                console.log("角度 %s", JSON.stringify(obj.rotation.toVector3()));
                console.log("位置 %s", JSON.stringify(obj.position));
                obj.traverse(function (child) {
                  if (child.isMesh) {
                    // console.log((child.material.emissive));
                    // child.material.emissive.set(1, 1, 1);
                    // console.log(JSON.stringify(child.material));
                    child.castShadow = true;
                    child.receiveShadow = true;
                    child.material.color.set(0xffffff);
                    child.material.bumpScale = 0;
                  }
                });

                this.supLoader.productMgr.root.add(obj)
              }

              //building 加载成功
              buildingPromise.then(building => {
                building.traverse(child => {
                  // console.log(child);
                  if (child.isMesh) {
                    child.castShadow = true;
                    // child.receiveShadow = true;
                    // console.log("child.name")
                    // console.log(child.name)
                    let material = this.supLoader.materialMgr.getMaterial(child.name);
                    if (material != null)
                      child.material = material;
                  }
                });
                this.scene.add(building);
                building.rotateY(THREE.MathUtils.degToRad(180));
                // console.log(building.rotation.toVector3());
                this.AfterResourceRequestFinished();
              });
            }).catch(error => {
              this.showErrorMessage('加载失败！')
              console.log("skyBoxPromise,supFilePromise:" + error);
            });
          });
        });
      },


      //旧版本加载天空盒逻辑
      loadSkyBox(skyBoxUrl) {
        SkyBoxMgr.getInstance().createSkyBoxAsync(skyBoxUrl).then(textureCube => {
          console.log("loadSkyBox");
          textureCube.format = THREE.RGBFormat;
          textureCube.mapping = THREE.CubeReflectionMapping;
          textureCube.encoding = THREE.sRGBEncoding;
          this.scene.background = textureCube;
        }).catch(error => {
          console.log('loadSkyBox:' + error);
        }).finally(function () {
          console.log("finally");
        });
      },

      //刷新场景
      update() {
        requestAnimationFrame(this.update);
        if(this.isSunlightAutoRotate){
         this.SunLightAutoRotate()
        }

        if(this.isRoam)
        {
          this.Roam();
        }
        this.scene.update();
      },

      Roam(){
        let delta = this.clock.getDelta();
        this.scene.character.update( delta );
      },

      SunLightAutoRotate(){
        let elapsed = this.clock.getElapsedTime()*0.1;
        this.scene.sunlight.position.set(Math.sin(elapsed)*50,Math.cos(elapsed)*50,0);
        this.scene.sunlight.lookAt(0,0,0);
      },

      //当资源请求完之后执行
      AfterResourceRequestFinished() {

        this.qrcodeUrl = window.location.href;
        console.log(this.qrcodeUrl);
        console.log(this.scene);

        this.$refs.root.appendChild(this.scene.renderer.domElement);
        this.$refs.root.addEventListener( 'keydown', this.scene.onKeyDown, false );
        this.$refs.root.addEventListener( 'keyup', this.scene.onKeyUp, false );
        this.update();
        this.loadingInstance.close();
        // this.$message.success('加载成功')
      },

      //显示message
      showErrorMessage(message) {
        this.$message.error(message)
      },


      //-------下面UI 逻辑
      //开启阳光渲染
      sunLightSwitchChange() {
        // console.log(this.sunLightSwitch)
        this.scene.sunlight.visible = this.sunLightSwitch;
        this.update();
      },
      sunLightAutoRotateSwitchChange(){
        this.update();
      },
      roamSwitchChange(){
        this.scene.character.root.visible=this.isRoam;
        this.scene.orbitControls.enableKeys=this.isRoam;
        this.update();
      },
      //设置阳光强度
      sunLightIntensityChange() {
        // console.log(this.sunLightIntensity)
        this.scene.sunlight.intensity = this.sunLightIntensity;
        this.update();
      },
      //设置阳光颜色
      sunLightColroChange() {
        let sunLightColorHex = this.sunLightColor.replace('#', '0x').toLowerCase()
        console.log(sunLightColorHex)
        this.scene.sunlight.color.setHex(sunLightColorHex);
        this.update();
      },
      resetView() {
        console.log('resetView');
        this.scene.camera.position.set(30, 30, 30);
        this.scene.orbitControls.target.set(0, 0, 0);
        this.scene.orbitControls.update();
        this.update();
      },
      //工具箱
      toolEdit() {
        console.log("toolEdit")
        this.toolsDialogVisible = true;
      },
      //工具箱对话框关闭
      toolsDialogClose() {
        this.toolsDialogVisible = false;
      },
      //商品清单
      productShow() {
        this.productsDialogVisible = true;
      },
      productsDialogClose() {
        this.productsDialogVisible = false;
      },
      //分享场景
      shareScene() {
        console.log("shareScene")
        this.shareDialogVisible = true;
        this.$nextTick(this.createQrcode);
      },
      //分享场景 对话框关闭
      shareDialogClose() {
        this.shareDialogVisible = false;
        this.qrcode.clear();
      },
      //关于我们
      showAboutUs() {
        console.log("showAboutUs")
        this.aboutUsVisible = true;
      },
      //关于我们 对话框关闭
      aboutUsClose() {
        this.aboutUsVisible = false;
      },
      //预约设计
      contactUsDesign() {
        console.log("contactUsDesign")
        this.contactUsDesignVisible = true;
      },
      //预约设计 对话框关闭
      contactUsDesignClose() {
        this.contactUsDesignVisible = false;
      },

      //购买商品
      productBuy() {
        window.open('https://www.iddd.com/', '_blank')
      },

      //生成二维码
      createQrcode() {
        if (this.qrcode === null) {
          this.qrcode = new QRCode('qrcode', {
            width: 150,
            height: 150,
            text: this.qrcodeUrl, // 二维码地址
            colorDark: "#000000",
            colorLight: "#ffffff",
          })
        }
        else {
          this.qrcode.makeCode(this.qrcodeUrl);
        }
      }
    },
  };
</script>

<style scoped lang="scss">

    .logo {
        position: fixed;
        left: 20px;
        top: 20px;
        width: 100px;
    }

    .tool {
        position: fixed;
        bottom: 0px;
        width: 100%;
        height: 52px;
        background-color: rgba(55, 55, 55, 0.9);
        z-index: 1;
        display: flex;
        justify-content: space-around;
        .el-button--primary {
            color: #fff;
            background-color: rgba(55, 55, 55, 0);
            border: 0px;
        }
        .el-button--primary:hover {
            background-color: rgba(55, 55, 55, 0);
            border: 0px;
        }
        .el-button--primary:focus {
            background-color: rgba(55, 55, 55, 0);
            border: 0px;
        }
    }

    .aboutUsP {
        text-indent: 2em;
    }

    .el-row {
        margin-bottom: 20px;
        &:last-child {
            margin-bottom: 0;
        }
        p {
            margin-bottom: 20px;
        }
    }

    #qrcode {
        display: flex;
        justify-content: center;
    }

    .productItem {
        position: relative;

        .productInfo {
            float: right;
            width: 50%;
            padding-right: 20px;
            .el-row {
                margin-top: 20px;
            }
        }
        .productBuyBtn {
            position: absolute;
            right: 10px;
            bottom: 10px;
        }

    }


</style>
